package com.baijia.services.impl;

import com.baijia.dao.UserDao;
import com.baijia.dao.po.User;
import com.baijia.services.IUserValidationService;
import com.baijia.util.JigouPasswordUtil;
import com.baijia.util.SecretCoverUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserValidationServiceImpl implements IUserValidationService {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean validatePassword(String mobile, String password) {
        log.info("validatePassword : mobile={}", SecretCoverUtil.coverMobileWithAsterisk(mobile));

        User user = userDao.getUserByMobile(mobile);
        if (user == null) {
            log.warn("validateUserByMobile : No user found.");
            return false;
        }

        try {
            if (!JigouPasswordUtil.validatePassword(password, user.getPassword())) {
                log.error("validatePassword : Password does not match.");
                return false;
            }
        } catch (Exception e) {
            log.error("validatePassword : Password does not match.");
            return false;
        }

        return true;
    }

    @Override
    public boolean validateUserByMobile(String mobile) {
        log.info("validateUserByMobile : mobile={}", SecretCoverUtil.coverMobileWithAsterisk(mobile));

        User user = userDao.getUserByMobile(mobile);
        if (user == null) {
            log.warn("validateUserByMobile : No user found.");
        }

        return user != null;
    }
}
